var  suff = new Date().getMilliseconds();

$(document).ready(function() {//加载前用url上token参数去登录我们系统
    localStorage.setExpire("locationHref","micro_analysis",sysTimeOut)//设置默认进入的模块

    var access_token=getQueryString("access_token");
    if(access_token!=null){
        getInfoByToken(access_token,function(userInfo){
            if(userInfo.hasOwnProperty("data")&&userInfo.data.hasOwnProperty("tjjcode")){
                getUserName(userInfo.data.tjjcode,function(user){
                    let req={
                        username:aesEncode(user.data.username) + "_" + suff,
                        password:aesEncode(userInfo.data.tjjcode) + "_" + suff,
                        client_id:"cloud",
                        client_secret:"cloud",
                        grant_type:"password"
                    }
                    login(req,function (res) {
                        if(res.status == 200&&res.data){
                            let data = res.data;
                            localStorage.setExpire('access_token',data.access_token,sysTimeOut);
                            localStorage.setExpire("token_type",data.token_type,sysTimeOut)
                            localStorage.setExpire("locationHref","micro_analysis",sysTimeOut)//设置默认进入的模块
                            rememberPassword(user);
                            getUserInfo();
                        }else{
                            console.log('直接登录失败：',JSON.parse(res.request.response).message)
                        }
                    })
                })
            }

        });
    }
});


layui.use(['layer', 'element', 'admin', 'index', 'laytpl', 'element','form','notice'], function () {
    var $ = layui.jquery;
    var form = layui.form;
    var notice = layui.notice;
    var userInfo = getAuthority();
    var Authorization;//请求接口用

    var keyword = "";//搜索关键词
    userInfo = JSON.parse(userInfo)
    //获取权限方法
    if (userInfo) {
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type + " " + access_token;

        getSystem();
        getHotKey();
    }
    var name = userInfo.sysUser.nickname;
    if(name === null || name === "null" || name === ""){
        name = userInfo.sysUser.username;
    }
    $('#user_name').html(name)
    $('.portal-logo').click(function () {
        location.href = webBaseUrl + '/index.html';
    })
    $('#editPassword').click(function(){
        openEditPassword();
    })
    $('#cancel-btn  ').click(function(){
        closeEditPassword();
    })
    //自定义验证规则
    form.verify({
        password: [
            /^[\S]{2,18}$/
            ,'密码必须2到18位，且不能出现空格'
        ],
        confirmPass:function(value){
            if($('input[name=password]').val() !== value)
                return '两次密码输入不一致！';
        }
    });
    // 监听提交
    form.on('submit(submit-psw)', function (data) {
        // admin.closeDialog('[lay-filter="submit-psw"]');
        // let password = JSON.parse(data.field.password);
        let password = data.field.password;
        updatePassword(password);
        return false;
    });
    let imgList = [
        { src: 'assets/images/login_sys/banner1.jpg' },
        { src: 'assets/images/login_sys/banner2.jpg' },
        { src: 'assets/images/login_sys/banner3.jpg' },
        { src: 'assets/images/login_sys/banner4.jpg' },
        { src: 'assets/images/login_sys/banner5.jpg' },
        ]
    let hotList = [{ value: 'GDP' }, { value: 'CPI' }, { value: 'PPI' }, { value: '社会消费品零售总额' }, { value: '总人口' }, { value: '粮食总量' }, { value: 'PMI' }, { value: 'PPI' }]
    let visualizationList = [{
        time: '2020-01-21',
        info: '四川省第四次全国经济普查公报（第一号）',
        src: 'assets/images/login_sys/4.png',
        url:webBaseUrl+'/page/chart/one.html'
    }, {
        time: '2020-01-21',
        info: '四川省第四次全国经济普查公报（第二号）',
        src: 'assets/images/login_sys/4.png',
        url:webBaseUrl+'/page/chart/two.html'
    }, {
        time: '2020-01-21',
        info: '四川省第四次全国经济普查公报（第三号）',
        src: 'assets/images/login_sys/4.png',
        url:webBaseUrl+'/page/chart/three.html'
    }, {
        time: '2020-01-21',
        info: '四川省第四次全国经济普查公报（第四号）',
        src: 'assets/images/login_sys/4.png',
        url:webBaseUrl+'/page/chart/four.html'
    }, {
        time: '2020-01-21',
        info: '四川省第四次全国经济普查公报（第五号）',
        src: 'assets/images/login_sys/4.png',
        url:webBaseUrl+'/page/chart/five.html'
    }, {
        time: '2020-01-21',
        info: '四川省第四次全国经济普查公报（第六号）',
        src: 'assets/images/login_sys/4.png',
        url:webBaseUrl+'/page/chart/six.html'
    }, {
        time: '2020-01-21',
        info: '四川省第四次全国经济普查公报（第七号）',
        src: 'assets/images/login_sys/4.png',
        url:webBaseUrl+'/page/chart/seven.html'
    }]
    //获取系统信息
    function getSystem() {
        let req = {
            type: 2
        }
        axios.get(portal_system.userSystem, {
            params: req,
            headers: {
                'Authorization': Authorization
            }
        })
            .then(function (response) {
                if (response.status == 200 && response.data.message == "success") {
                    var data = response.data.data;
                    //系统
                    data.map(item=>{
                        item.imgurl = "assets/images/index/" + item.systemIdentifier + ".png"
                        if(item.name == "数据可视化子系统"){
                            item.url = item.url + "?username=" + userInfo.sysUser.username;
                        }
                        //判断本地图片是否存在
                        var ImgObj=new Image();
                        ImgObj.src= item.imgurl;
                        setTimeout(()=>{

                            if(ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0))
                            {
                                item.imgurl = "assets/images/index/" + item.systemIdentifier + ".png"
                            } else {
                                item.imgurl = "assets/images/index/micro_analysis.png"
                            }
                        },300)
                        return item
                    })
                    var system_str = template("template-system-tmpl", { data });
                    document.getElementById("system_box").innerHTML = system_str;

                    var swiper_system = new Swiper('.system-swiper', {
                        pagination: '.system-pagination',
                        slidesPerView: 5,
                        paginationClickable: true,
                        spaceBetween: 30
                    });
                    $('.system-item').click(function () {
                        let system_id = $(this).attr('data-id')
                        let openType = $(this).attr('data-open')
                        let url = $(this).attr('data-url')
                        if(openType == "1"){
                            window.open(url);
                        }else {
                            localStorage.setItem('system_id',system_id)
                            location.href = webBaseUrl + '/system.html';
                        }
                    })

                    var locationHref = localStorage.getExpire("locationHref")
                    if(locationHref!=""&&locationHref!=null){
                        $('.'+locationHref).click();
                    }
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    //轮播
    var image_str = template("template-swiper-image-tmpl", { imgList });
    document.getElementById("swiper_img").innerHTML = image_str;

    //热词
    function getHotKey() {
        axios.get(portal_system.hotkey, {
            headers: {
                'Authorization': Authorization
            }
        })
            .then(function (response) {
                if (response.status == 200 && response.data.message == "success") {
                    var data = response.data.data;
                    var hot_str = template("template-search-hot-tmpl", { data });
                    document.getElementById("search_hot").innerHTML = hot_str;
                    $("#search_hot p").click(function () {
                        window.open(searchUrl + `/#/search${$(this).text()}`)
                    })
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    //可视化
    var visualization_str = template("template-visualization-tmpl", { visualizationList });
    document.getElementById("visualization_box").innerHTML = visualization_str;
    //远程检索
    $("#getTips").bind("input  propertychange", function() {
        keyword = $(this).val();
        if(keyword!=""){
            remoteSearch()
        }else{
            $("#hot-modle").css("display","none")
        }
    })
    $("#search_btn").click(function () {
        if($("#getTips").val()){
            window.open( searchUrl + `/#/search${$("#getTips").val()}`)
        }

    })
    $('#getTips').bind('keyup', function(event) {
        if (event.keyCode == "13") {
            //回车执行查询
            window.location = searchUrl + `/#/search${$("#getTips").val()}`
        }
    });
    function remoteSearch() {
        let req = {
            keyword: keyword,
            mitmid: -1
        };
        axios.get(portal_system.getTips, {
            params: req,
            headers: {
                'Authorization': Authorization
            }
        })
            .then(function (response) {
                if (response.status == 200 && response.data.message == "success") {
                    var data = response.data.data;
                    if(data.length&&keyword!=""){
                        $("#hot-modle").css("display","block")
                        var searchData = template("template-searchkey-tmpl", { data });
                        document.getElementById("hot-modle").innerHTML = searchData;
                        $("#hot-modle p").click(function () {
                            window.open(searchUrl + `/#/search${$(this).text()}`)
                        })
                    }else {
                        $("#hot-modle").css("display","none")
                    }
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    //
    $(".visualization-item").click(function () {
        window.open($(this).attr("data-url"));
    })
    var swiper = new Swiper('.banner-swiper', {
        pagination:{
            el:'.banner-pagination',
            clickable:true
        },
        loop: true,
        autoplay: {
            delay: 10000,//1秒切换一次
            stopOnLastSlide: false,
            disableOnInteraction: false
        },
    });
    var swiper_visualization = new Swiper('.visualization-swiper', {
        slidesPerView: 5,
        spaceBetween: 30,
        pagination: {
          el: '.visualization-pagination',
          clickable: true,
        }
    });

    //打开密码修改弹窗
    function openEditPassword() {
        layer.open({
            type:1,
            id: 'layer-psw',
            title: '修改密码',
            shade: .1,
            area: '360px',
            content:$('#editPasswordBox')
        });
    }

    //关闭密码修改弹窗
    function closeEditPassword() {
        layer.closeAll(); //疯狂模式，关闭所有层
    }
    //更新密码
    function updatePassword(password) {
        var formData = new FormData();
        formData.append("password",password);
        axios({
            method: 'put',
            url:loginUrl.editUserPassword,
            data:formData,
            headers:{
                'Authorization': Authorization}
        })
            .then(function (response) {
                debugger
                if(response.status == 200&&response.data.message=="success"){
                    notice.msg("修改密码操作成功", {icon: 1,timeout:2000});
                    setTimeout(function () {
                        location.href=loginPageUrl;
                        localStorage.clear();
                        sessionStorage.clear();
                    },2000)
                }else {
                    notice.msg(Jresponse.data.message, {icon: 2,timeout:2000});
                    console.log(response.data)
                }
            })
            .catch(function (error) {
                notice.msg(JSON.parse(error.request.response).message, {icon: 2,timeout:2000});
                console.log(error);
            });
    }

});
